use crate::rtmp::chunk::ChunkInfo;
use crate::rtmp::messages::define::{msg_type_id, RtmpMessageData};
use crate::rtmp::messages::errors::MessageError;
use crate::rtmp::protocol_control_messages::reader::ProtocolControlMessageReader;
use crate::rtmp::user_control_messages::reader::EventMessagesReader;
use bytesio::bytes_reader::BytesReader;
use xflv::amf0::amf0_markers;
use xflv::amf0::amf0_reader::Amf0Reader;

// 消息解析器结构体
pub struct MessageParser {
    chunk_info: ChunkInfo,
}

impl MessageParser {
    pub fn new(chunk_info: ChunkInfo) -> Self {
        Self { chunk_info }
    }

    // 解析消息
    pub fn parse(self) -> Result<Option<RtmpMessageData>, MessageError> {
        let mut reader = BytesReader::new(self.chunk_info.payload);

        match self.chunk_info.message_header.msg_type_id {
            msg_type_id::COMMAND_AMF0 | msg_type_id::COMMAND_AMF3 => {
                // 处理 AMF0 或 AMF3 命令消息
                if self.chunk_info.message_header.msg_type_id == msg_type_id::COMMAND_AMF3 {
                    // 读取一个字节，AMF3特有
                    reader.read_u8()?;
                }
                // AMF0 读取器
                let mut amf_reader = Amf0Reader::new(reader);

                // 读取名称和事务 ID
                let command_name = amf_reader.read_with_type(amf0_markers::STRING)?;
                let transaction_id = amf_reader.read_with_type(amf0_markers::NUMBER)?;

                // 读取命令对象
                let command_obj_raw = amf_reader.read_with_type(amf0_markers::OBJECT);
                let command_obj = match command_obj_raw {
                    Ok(value) => value,
                    Err(_) => amf_reader.read_with_type(amf0_markers::NULL)?,
                };

                let others = amf_reader.read_all()?;

                // 返回 AMF0 命令数据
                return Ok(Some(RtmpMessageData::Amf0Command {
                    command_name,
                    transaction_id,
                    command_object: command_obj,
                    others,
                }));
            }

            msg_type_id::AUDIO => {
                // 处理音频数据
                log::trace!(
                    "receive audio message, msg length is {}",
                    self.chunk_info.message_header.msg_length
                );
                return Ok(Some(RtmpMessageData::AudioData {
                    data: reader.extract_remaining_bytes(),
                }));
            }

            msg_type_id::VIDEO => {
                // 处理视频数据
                log::trace!(
                    "receive video message, msg length is {}",
                    self.chunk_info.message_header.msg_length
                );
                return Ok(Some(RtmpMessageData::VideoData {
                    data: reader.extract_remaining_bytes(),
                }));
            }

            msg_type_id::USER_CONTROL_EVENT => {
                // 处理用户控制事件消息
                log::trace!(
                    "receive user control event, msg length is {}",
                    self.chunk_info.message_header.msg_length
                );
                let data = EventMessagesReader::new(reader).parse_event()?;
                return Ok(Some(data));
            }

            msg_type_id::SET_CHUNK_SIZE => {
                // 处理设置块大小消息
                let chunk_size = ProtocolControlMessageReader::new(reader).read_set_chunk_size()?;
                return Ok(Some(RtmpMessageData::SetChunkSize { chunk_size }));
            }

            msg_type_id::ABORT => {
                // 处理中断消息
                let chunk_stream_id =
                    ProtocolControlMessageReader::new(reader).read_abort_message()?;
                return Ok(Some(RtmpMessageData::AbortMessage { chunk_stream_id }));
            }

            msg_type_id::ACKNOWLEDGEMENT => {
                // 处理确认消息
                let sequence_number =
                    ProtocolControlMessageReader::new(reader).read_acknowledgement()?;
                return Ok(Some(RtmpMessageData::Acknowledgement { sequence_number }));
            }

            msg_type_id::WIN_ACKNOWLEDGEMENT_SIZE => {
                // 处理确认窗口大小消息
                let size =
                    ProtocolControlMessageReader::new(reader).read_window_acknowledgement_size()?;
                return Ok(Some(RtmpMessageData::WindowAcknowledgementSize { size }));
            }

            msg_type_id::SET_PEER_BANDWIDTH => {
                // 处理设置对等带宽消息
                let properties =
                    ProtocolControlMessageReader::new(reader).read_set_peer_bandwidth()?;
                return Ok(Some(RtmpMessageData::SetPeerBandwidth { properties }));
            }

            msg_type_id::DATA_AMF0 | msg_type_id::DATA_AMF3 => {
                return Ok(Some(RtmpMessageData::AmfData {
                    raw_data: reader.extract_remaining_bytes(),
                }));
            }

            msg_type_id::SHARED_OBJ_AMF3 | msg_type_id::SHARED_OBJ_AMF0 => {
                // 处理共享对象消息（AMF3或AMF0），当前未实现
            }

            msg_type_id::AGGREGATE => {
                // 处理聚合消息，当前未实现
            }

            _ => {
                // 处理未识别的消息类型
            }
        }
        log::warn!(
            "the msg_type_id is not processed: {}",
            self.chunk_info.message_header.msg_type_id
        );

        Ok(None)
    }
}
